import baseConfig from '@/config/base-config'
import { localStore } from '@/utils/storage'
import { Base64 } from 'js-base64'
import type { IInternalAxiosRequestConfig } from '@/utils/http/type'
import { ContentTypeEnum } from '@/utils/http/type'

export const normalRequest = (config: IInternalAxiosRequestConfig) => {
  //处理系统参数
  if (baseConfig.CLIENT_CONFIG.GRAY_VERSION) {
    config.headers.gray_version = baseConfig.CLIENT_CONFIG.GRAY_VERSION
  }
  const applicationId = localStore.get<string>('applicationId')
  if (applicationId) {
    config.headers.ApplicationId = applicationId
  }
  config.headers.authorization = `${Base64.encode(
    `${baseConfig.CLIENT_CONFIG.CLIENT_ID}:${baseConfig.CLIENT_CONFIG.CLIENT_SECRET}`
  )}`
  // Get 请求添加时间戳防止缓存
  if (['get', 'GET'].includes(config?.method || '')) {
    config.data = {
      ...config.data
    }
    config.params = config.data
    delete config.data
    config.headers['Content-Type'] = ContentTypeEnum.FORM_URLENCODED
  }
  // 删除值为null或者undefined的参数
  for (const [key, value] of Object.entries(config.data || {})) {
    if (value === null || value === undefined) delete config.data[key]
  }
}
